package com.xh.bussiness.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xh.bussiness.system.bean.request.CourseSystemRequest;
import com.xh.bussiness.system.bean.request.DictionaryRequest;
import com.xh.bussiness.system.bean.request.SaveCourseSystemRequest;
import com.xh.bussiness.system.dao.CourseSystemMapper;
import com.xh.bussiness.system.model.CourseSystem;
import com.xh.bussiness.system.model.Dictionary;
import com.xh.bussiness.system.service.ICourseSystemService;
import com.xh.bussiness.system.service.IDictionaryService;
import com.xh.core.service.impl.BaseServiceImpl;
import com.xh.core.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.xh.core.bean.XhPage;
import org.springframework.util.CollectionUtils;

import java.util.*;

/**
 * <p>
 * 课程体系 服务实现类
 * </p>
 *
 * @author Pitt
 * @since 2020-11-18
 */
@Service
public class CourseSystemServiceImpl extends BaseServiceImpl<CourseSystemMapper, CourseSystem> implements ICourseSystemService {

    @Autowired
    private IDictionaryService dictionaryService;

    @Override
    public XhPage queryCourseSystemPage(XhPage page, CourseSystemRequest bean) {
        QueryWrapper qw = new QueryWrapper<CourseSystem>();
        //拼装条件
        qw = prepareParams(bean, qw);

        return (XhPage) this.dao.selectPage(page, qw);
    }

    @Override
    public List queryCourseSystem(CourseSystemRequest bean) {
        QueryWrapper qw = new QueryWrapper<CourseSystem>();
        //拼装条件
        qw = prepareParams(bean, qw);

        List<CourseSystem> list = this.dao.selectList(qw);

        List<CourseSystem> datas = new ArrayList<>();
        if (!CollectionUtils.isEmpty(list)) {
            for (CourseSystem courseSystem : list) {
                Dictionary dictionary = dictionaryService.getById(courseSystem.getRelationValue());
                if (dictionary != null) {
                    courseSystem.setRelationName(dictionary.getName());
                    datas.add(courseSystem);
                }
            }
        }
        return datas;
    }

    @Override
    public Map<String, Object> queryCourseSystemBySubject(String subjectId, String[] typeCode) {
        Map<String, Object> retMap = new HashMap<>();
        //课程体系：年级、学期、教材版本、班级类型
        if (typeCode == null || typeCode.length <= 0) {
            typeCode = new String[]{"GRADE", "SEMESTER", "TEACH_BOOK_VERSION", "COURSE_TYPE"};
        }
        DictionaryRequest dictionaryRequest = new DictionaryRequest();
        dictionaryRequest.setStatus(0);

        CourseSystemRequest courseSystemRequest = new CourseSystemRequest();
        courseSystemRequest.setSubjectId(subjectId);
        for (String type : typeCode) {
            //获取所有基础项
            dictionaryRequest.setTypeCode(type);
            List<Dictionary> dictionaryList = dictionaryService.queryDictionary(dictionaryRequest);
            //查询已经设置过的基础项
            courseSystemRequest.setRelationType(type);
            List<CourseSystem> courseSystemTypeItems = this.queryCourseSystem(courseSystemRequest);

            if (!CollectionUtils.isEmpty(dictionaryList) && !CollectionUtils.isEmpty(courseSystemTypeItems)) {
                for (Dictionary dictionary : dictionaryList) {
                    //课程体系是否配置改项
                    Optional<CourseSystem> first = null;

                    first = courseSystemTypeItems.stream().filter(item -> item.getRelationValue().equals(dictionary.getId())).findFirst();
                    dictionary.setCheck(first.isPresent() ? true : false);
                }
            }
            retMap.put(type, dictionaryList);
        }
        return retMap;
    }

    @Override
    public boolean saveOrUpdateCourseSystemBySubjectId(CourseSystem courseSystem) {
        QueryWrapper<CourseSystem> qw = new QueryWrapper<>();
        qw.eq("subject_id", courseSystem.getSubjectId());
        qw.eq("relation_type", courseSystem.getRelationType());
        qw.eq("relation_value", courseSystem.getRelationValue());
        //存在该配置项证明是取消了该项，直接删除
        CourseSystem exists = this.dao.selectOne(qw);
        if (exists != null) {
            this.dao.deleteByParam(courseSystem.getSubjectId(), courseSystem.getRelationType(), courseSystem.getRelationValue());
            return true;
        } else {
            return this.insert(courseSystem);
        }
    }

    @Override
    public boolean batchSaveOrUpdateCourseSystemBySubjectId(SaveCourseSystemRequest request) {
        this.dao.deleteByParam(request.getSubjectId(), request.getRelationType(), null);
        //取消全部勾选
        if (!CollectionUtils.isEmpty(request.getDictionaries())) {
            List<CourseSystem> courseSystems = new ArrayList<>();
            for (Dictionary dictionary : request.getDictionaries()) {
                CourseSystem courseSystem = new CourseSystem();
                courseSystem.setSubjectId(request.getSubjectId());
                courseSystem.setSubjectName(request.getSubjectName());
                courseSystem.setRelationValue(dictionary.getId());
                courseSystem.setRelationName(dictionary.getName());
                courseSystem.setRelationType(request.getRelationType());

                courseSystems.add(courseSystem);
            }
            return this.batchInsert(courseSystems);
        }
        return true;
    }

    @Override
    public List<Dictionary> queryDictionaryByCourseSystem(String subjectCode, String typeCode) {
        return this.dao.queryDictionaryByCourseSystem(subjectCode, typeCode);
    }

    @Override
    public List<Dictionary> queryLikeDictionaryByCourseSystem(String subjectCode,String name,String typeCode) {
        return this.dao.queryLikeDictionaryByCourseSystem(subjectCode, name ,typeCode);
    }

    /**
     * 准备条件
     *
     * @param bean
     * @param qw
     */
    private QueryWrapper prepareParams(CourseSystemRequest bean, QueryWrapper qw) {
        if (bean.getIds() != null && bean.getIds().length > 0) {
            qw.in("id", bean.getIds());
        }
        if (!StringUtils.isEmpty(bean.getSubjectId())) {
            qw.eq("subject_id", bean.getSubjectId());
        }
        if (!StringUtils.isEmpty(bean.getRelationType())) {
            qw.eq("relation_type", bean.getRelationType());
        }
        if (!StringUtils.isEmpty(bean.getRelationValue())) {
            qw.eq("relation_value", bean.getRelationValue());
        }
        return qw;
    }
}
